<!--
 * @Author: zhi1hw hanwei@zhi1tech.com
 * @Date: 2024-06-28 20:47:19
 * @LastEditors: zhi1hw hanwei@zhi1tech.com
 * @LastEditTime: 2025-01-06 14:52:27
 * @FilePath: \code\src\views\home\components\transfer.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="wrapper" v-if="!state.isShowLoadding" @click.stop>
    <div class="yindaoye">
      <div class="guide">
        <!-- <video
            class="video-background"
            id="video"
            loop
            muted
            playsinline
            preload="metadata"
            autoplay
            poster="@/assets/images/video-bg.jpg"
            x5-video-player-type="h5"
          >
            <source src="@/assets/images/guide-video.mp4" type="video/mp4" />
          </video> -->
        <!-- <img src="@/assets/images/video-bg.jpg" alt="" > -->
      </div>
      
      <div class="robot">
        <img src="@/assets/images/robot1.png" alt="" style="width: 82px; height: 82px; margin:100px auto 30px auto" />
        <printHtml
          :homeInfo="state.homeInfo"
          @listenPrintHtml="listenPrintHtml"
        />
      
        <!--          <div class="today-hot" v-if="state.homeInfo?.dailyNews">-->
        <div class="today-hot">
          <template v-if="state.isPrivileges">
            <template v-if="state.homeInfo?.dailyNews.length > 0">
              <div class="title">
                <span>至一热搜</span> <span class="line"></span>
                <span class="subtitle">最新内容早知道</span>
              </div>
              <div class="list">
                <div class="nav-tab">
                  <div
                    class="nav-item"
                    :class="state.navIndex === index ? 'active' : ''"
                    v-for="(i, index) in state.homeInfo?.dailyNews?.map((j:any) => j.typeName)"
                    :key="index"
                    @click="state.navIndex = index"
                  >
                    <div class="item-text">{{ i }}</div>
                  </div>
                </div>
                <template
                  v-if="
                    state.homeInfo?.dailyNews[state.navIndex].list &&
                    state.homeInfo?.dailyNews[state.navIndex].list.length > 0
                  "
                >
                  <div class="scroll-box">
                    <div
                      class="item"
                      v-for="i in state.homeInfo?.dailyNews[state.navIndex]
                        .list"
                      :key="i"
                      @click="bindClick(i.quizContent)"
                    >
                      <div>
                        <div class="point"></div>
                        {{ i.quizContent }}
                      </div>
                      <div>
                        <img src="@/assets/images/arrow.png" alt="" />
                      </div>
                    </div>
                  </div>
                </template>
                <template v-else>
                  <van-empty
                    image-size="0"
                    description="至一AI助手正在努力学习中"
                  />
                </template>
              </div>
              <div
                class="opt-text"
                @click="toHome"
                :class="state.isPrintEnd ? 'end-opt-text' : ''"
              >
                立即体验
              </div>
            </template>
          </template>
          <template v-else>
            <div class="title">
              <span class="privileges-span">
                {{
                  state.firstFunctionApply
                    ? "暂时没有权限哦！请点击下方按钮进行申请"
                    : "您的申请正在审核中!"
                }}</span
              >
            </div>
            <el-dialog
              v-if="state.firstFunctionApply"
              title="至一AI助手功能申请"
              :visible.sync="detailVisible"
              width="35%"
            >
              <van-form class="applySubmit">
                <van-field
                  v-model="message"
                  rows="2"
                  autosize
                  label="申请理由"
                  type="textarea"
                  maxlength="50"
                  placeholder="请输入申请原因"
                  show-word-limit
                />
                <!--                  <span v-if="state.isSubmitting">已经提交过了，请勿重复提交</span>-->
                <div style="margin: 16px">
                  <van-button
                    round
                    block
                    type="primary"
                    native-type="submit"
                    :disabled="state.isSubmitting"
                    @click="onSubmit"
                  >
                    提交
                  </van-button>
                </div>
              </van-form>
            </el-dialog>
          </template>
        </div>
      </div>
      <div class="transfer-header">
        <div class="weather">
          <div class="area">
            <span class="area-name" @click="state.isShowArea = true"
              ><van-icon name="location-o" />{{
                state.homeInfo?.cityName || ""
              }}</span
            >
            <span v-if="state.homeInfo">
              <i :class="'qi-' + state.homeInfo?.currWeather?.icon"></i>
              <template v-if="state.homeInfo?.currWeather?.temp">
                &nbsp;{{ state.homeInfo?.currWeather?.temp }}℃</template
              >

              &nbsp;&nbsp;&nbsp;{{ state.homeInfo?.currWeather?.text }}</span
            >
          </div>
          <span
            >{{ moment().format("MM-DD") }} &nbsp;&nbsp;
            {{ weekdays[moment().format("d")] }}</span
          >
        </div>
        <!-- <div class="skip" @click="toHome">跳过</div> -->
      </div>
      <div class="ver">{{ ver }}</div>
    </div>
  </div>

  <van-overlay
    :show="state.isShowLoadding"
    z-index="100"
    style="display: flex; align-items: center; justify-content: center"
  >
    <van-loading />
  </van-overlay>

  <van-popup
    v-model:show="state.isShowArea"
    position="bottom"
    :style="{ height: '30%' }"
  >
    <van-area
      title="地区选择"
      :area-list="areaList"
      :columns-num="2"
      @confirm="areaConfirm"
      @cancel="state.isShowArea = false"
    />
  </van-popup>
</template>

<script setup lang="ts">
import { themeStore, ITheme } from "../store/modules/theme";
import { useRoute, useRouter } from "vue-router";
import printHtml from "./demo.vue";
import moment from "moment";
import { areaList } from "@vant/area-data";
const themeColor: ITheme = themeStore().theme;
import {
  ComponentInternalInstance,
  getCurrentInstance,
  inject,
  onMounted,
  onUnmounted,
  reactive,
  watch,
  defineProps,
  provide,
} from "vue";
import { showDialog } from "vant";
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

provide("themeColor", themeColor);
const state = reactive({
  isLoadEnd: false,
  isPrintEnd: false,
  homeInfo: null,
  isShowBg: false,
  isShowArea: false,
  isShowLoadding: true,
  navIndex: 0,
  isSubmitting: false,
  isPrivileges: false,
  firstFunctionApply: false,
});
let message = "";
const router = useRouter();
const listenPrintHtml = (e: boolean) => {
  state.isPrintEnd = e;
};
const weekdays = [
  "星期日",
  "星期一",
  "星期二",
  "星期三",
  "星期四",
  "星期五",
  "星期六",
];
// 省市区选择
const areaConfirm = (e: any) => {
  let homeInfo = JSON.parse(JSON.stringify(state.homeInfo));
  homeInfo.cityName = e.selectedOptions[e.selectedOptions.length - 1].text;
  localStorage.setItem("area", JSON.stringify(e));
  state.homeInfo = homeInfo;
  state.isShowArea = false;
  getHomeInfo(e.selectedOptions[e.selectedOptions.length - 1].text);
};
const toLogin = (code: any, isBackLoading: boolean, type: number) => {

  // /dev/AI/wechatApi/login
  // /dev/AI/wechatApi/backLogin
  const url = isBackLoading
    ? process.env.VUE_APP_BASE_API_URL + "/wechatApi/backLogin"
    : process.env.VUE_APP_BASE_API_URL + "/wechatApi/login";
  proxy?.$api
    .post(url, {
      code: code,
      type: type,
    })
    .then((res: any) => {
      
      if (res.code === 200 && res.data) {
        let email = res.data.user?.email?.split("@")[0];
        let isPrivileges = res.data.privileges;

        themeStore().setCount(email || "");
        localStorage.setItem("userInfo", JSON.stringify(res.data));
        localStorage.setItem("token", res.data.token);
        let area = localStorage.getItem("area")
          ? JSON.parse(localStorage.getItem("area"))
          : "";
        state.isPrivileges = isPrivileges;
        state.firstFunctionApply = res.data.firstFunctionApply;
     
        if (
          res.data.userConfig &&
          res.data.userConfig.length > 0 &&
          res.data.userConfig[0].value != "true" &&
          isPrivileges
        ) {
          toHome();
        } else {
          getHomeInfo(
            area && area.selectedOptions
              ? area.selectedOptions[area.selectedOptions.length - 1].text
              : "上海"
          );
        }
        state.isShowLoadding = false;
      } else {
        if (type === 2) {
          if (process.env.NODE_ENV === "development") {
            // location.href = `${process.env.VUE_APP_BASE_API}AI/wechatApi/authorize`;
            state.isShowLoadding = false;
          } else if (process.env.NODE_ENV === "test") {
            location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorizeAAD`;
          } else if (process.env.NODE_ENV === "production") {
            location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorizeAAD`;
          }
        }
        //  if(/wxwork/i.test(navigator.userAgent)) {
        //   if(process.env.NODE_ENV === 'development') {
        //     location.href = `${process.env.VUE_APP_BASE_API}AI/wechatApi/authorize`;
        //   } else if(process.env.NODE_ENV === 'test') {
        //       location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorizeAAD`;
        //   } else {
        //       location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorizeAAD`;
        //   }
        // } else  if (/micromessenger/i.test(navigator.userAgent)) {
        //   // 微信浏览器
        // }
      }
    });
};

const getServerIP = async () => {
  try {
    const response = await fetch("https://api.ipify.org?format=json");
    const data = await response.json();
    return data.ip;
  } catch (error) {
    return null;
  }
};

const getHomeInfo = async (city: string) => {
  proxy?.$api
    .get(process.env.VUE_APP_BASE_API_URL + "/wechatApi/getHomeInfo", {
      cityName: city || "",
      ip: await getServerIP(),
    })
    .then((res: any) => {
      if (res.code === 200) {
        let area = localStorage.getItem("area")
          ? JSON.parse(localStorage.getItem("area"))
          : "";
        if (area) {
          res.data.cityName =
            area.selectedOptions[area.selectedOptions.length - 1].text;
        }
        localStorage.setItem("homeInfo", JSON.stringify(res.data));
        state.homeInfo = res.data;
        // if(localStorage.getItem('isPreview') === 'true') {
        //   proxy?.$router.replace({path: "/home", query:{
        //     sessionId: localStorage.getItem('sessionId'),
        //   }});
        // }
      }
    });
};
const bindClick = (e: string) => {
  if (!localStorage.getItem("userInfo")) {
    proxy?.$showToast("用户信息获取失败");
    return;
  }
  proxy?.$router.replace({
    path: "/home",
    query: {
      sendText: e,
    },
  });
};
const toHome = () => {
  if (!localStorage.getItem("userInfo")) {
    proxy?.$showToast("用户信息获取失败");
    return;
  }
  // location.href = "https://" + window.location.host + "/BeiGeneAI/#/home"
  proxy?.$router.replace("/home");
};
const ver = process.env.VUE_APP_VERSION;
const isMobile = function () {
  const userAgent = navigator.userAgent.toLowerCase();
  return /iphone|ipod|android|windows phone|blackberry|bb10|mobi|xoom|tablet|mobile/i.test(
    userAgent
  );
};
onMounted(() => {
  // localStorage.removeItem("userInfo");
  // localStorage.removeItem("token");

  // // playVideo()
  // // '2b64fca4a698a120b19580efc1dff51a'
  // let params: any = proxy?.$utils.getUrlParam();
  // if (params && (params.code || params.userCode || params.id_token)) {
  //   const LOGIN_TYPE = params.code || params.userCode ? 2 : 1;
  //   toLogin(
  //     params.code || params.userCode || params.id_token || "",
  //     params.code || params.id_token ? false : true,
  //     LOGIN_TYPE
  //   );
  // } else {
  //   state.isShowLoadding = false;
  //   if (process.env.NODE_ENV === "development") {
  //     location.href = `${process.env.VUE_APP_BASE_API}/BeiGeneAI/#/transfer?userCode=john.oyler@beigene.com`;
  //   } else if (process.env.NODE_ENV === "test") {
  //     if(isMobile()) {
  //       location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorize`;
  //     } else {
  //       location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorizeAAD`;
  //     }
  //   } else {
  //     if(isMobile()) {
  //       location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorize`;
  //     } else {
  //       location.href = `${process.env.VUE_APP_BASE_API}AIBackend/Api/wechatApi/authorizeAAD`;
  //     }
  //   }
    
  // }
  // setTimeout(() => {
  //   state.isShowBg = true;
  // }, 5000);
    router.push('/home') 
});

const onSubmit = async () => {
  // if (state.isSubmitting) return;
  // 防止重复提交

  state.isSubmitting = true; // 设置为正在提交

  // 获取并解析用户信息
  let userInfo = localStorage.getItem("userInfo");
  if (userInfo) {
    userInfo = JSON.parse(userInfo); // 解析为对象
  } else {
    console.error("未找到用户信息");
    state.isSubmitting = false;
    return;
  }

  // 获取 user.email
  const email = userInfo.user?.email;
  if (!email) {
    console.error("用户邮箱未找到");
    state.isSubmitting = false;
    return;
  }

  try {
    // 构建请求体
    const requestBody = {
      email: email, // 提交 user.email
      reason: message,
      isDispose: true,
      applyTime: Date.now(), // 使用 ISO 时间格式
    };
    const url =
      process.env.VUE_APP_BASE_API_URL + "/functionApply/insertFunctionApply";
    proxy?.$api.post(url, requestBody).then((res: any) => {
      if (res.code == 200) {
        state.isSubmitting = true;
        state.firstFunctionApply = false;
        showDialog({
          message: "申请成功!",
        });
      } else {
        showDialog({
          message: res.msg,
        });
      }
    });
    // proxy?.$router.replace("/home");
  } catch (error) {
    // 处理错误
    console.error("提交失败:", error);
  } finally {
    state.isSubmitting = false; // 恢复状态
  }
};
</script>

<style lang="scss" scoped>
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  .yindaoye {
    .transfer-header {
      position: absolute;
      top: 30px;
      padding: 0 30px;
      display: flex;
      justify-content: space-between;
      width: 100%;
      left: 0;
      z-index: 102;
      .weather {
        font-size: 28px;
        font-weight: 400;
        letter-spacing: 0px;
        line-height: 40px;
        color: #28334a;
        text-align: left;
        vertical-align: top;
        display: flex;
        justify-content: space-between;
        width: 100%;
        .area {
          display: flex;
          align-items: center;
        }
        span {
          display: block;
          margin-bottom: 5px;
          margin-right: 20px;
        }
      }
    }
    .skip {
      padding: 12px 28px;
      height: 68px;
      border-radius: 40px;
      background: rgba(0, 45, 87, 0.2);
      font-size: 32px;
      font-weight: 500;
      letter-spacing: 0px;
      color: #ffffff;
    }
    .guide {
      position: fixed;
      top: 0;
      left: 0;
      min-width: 100%;
      min-height: 100%;
      width: auto;
      height: auto;
      z-index: -1;
      background: url("../assets/images/video-bg.jpg");
      background-size: cover;
      .video-background {
        width: 100%;
      }
      img {
        width: 100%;
      }
    }
    .robot {
      position: absolute;
      left: 0;
      right: 0;
      margin: auto;
      top: 2%;
      text-align: center;
      z-index: 100;
   
      .today-hot {
        border-radius: 20px 20px 20px 20px;
        background: #F1F8FE;

        box-shadow: 0px 0px 10px rgba(0, 125, 235, 0.3);
        //padding: 34px 42px;
        // width: 80%;
        // height: 2rem;
        margin: 0 auto;
        .scroll-box {
          height: 400px;
          overflow: scroll;
          &::-webkit-scrollbar {
            display: none;
          }
        }
        .title {
          font-size: 32px;
          font-weight: 400;
          letter-spacing: 0px;
          line-height: 19.2px;
          color: #5393cf;
          text-align: left;
          margin: 16px 0 36px;
          margin-left: 1rem;
          font-weight: bold;
          float: left;
          clear: both;
          display: block;
          width: 100%;
          display: flex;
          align-items: center;
          gap: 18px;
          .line {
            width: 1px;
            height: 30px;
            opacity: 1;
            background: rgba(83, 147, 207, 1);
          }
          .applySubmit {
            display: block;
            width: 100%;
            display: flex;
            align-items: center;
          }
          .subtitle {
            font-size: 28px;
            font-weight: 400;
            letter-spacing: 0px;
            line-height: 33.6px;
            color: rgba(83, 147, 207, 0.5);
            text-align: left;
            padding-top: 2px;
          }
        }
        .list {
          width: 100%;
          clear: both;
          .nav-tab {
            display: flex;
            align-items: flex-start;
            justify-content: space-between;
            .nav-item {
              font-size: 28px;
              font-weight: 500;
              letter-spacing: 0px;
              line-height: 38px;
              color: rgba(83, 147, 207, 0.5);
              text-align: left;
              vertical-align: top;
              position: relative;
              .item-text {
                position: relative;
                z-index: 2;
              }
              &.active {
                color: #333;
                &::after {
                  content: "";
                  display: block;
                  position: absolute;
                  background: linear-gradient(
                    153.12deg,
                    rgba(92, 178, 255, 1) 17.78%,
                    rgba(255, 177, 177, 1) 100%
                  );
                  height: 8px;
                  width: 100%;
                  bottom: 2px;
                  z-index: 1;
                }
              }
            }
          }
          .item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            opacity: 1;
            border-radius: 12px;
            background: rgba(83, 147, 207, 0.1);
            border-radius: 12px;
            margin-top: 20px;
            font-size: 24px;
            font-weight: 400;
            letter-spacing: 0px;
            line-height: 40px;
            color: rgba(83, 147, 207, 1);
            text-align: left;
            vertical-align: top;
            padding: 24px;
            & > div {
              display: flex;
              align-items: center;
            }
            .point {
              width: 5px;
              height: 5px;
              opacity: 1;
              background: #5393cf;
              border-radius: 50%;
              margin-right: 16px;
            }
          }
        }
      }
      .opt-text {
        padding: 24px 0;
        border-radius: 44px;
        background: rgba(83, 147, 207, 1);
        box-shadow: 0px 4px 4px rgba(81, 136, 184, 0.5);
        font-size: 32px;
        font-weight: 700;
        letter-spacing: 0px;
        color: #ffffff;
        width: 440px;
        margin: 0 auto;
        margin-top: 40px;
        opacity: 0;
      }
      .end-opt-text {
        animation: upDown 500ms ease-in-out;
        opacity: 1;
      }
      img {
        width: 60%;
        margin-top: -4%;
      }
    }
  }
  .ver {
    position: absolute;
    bottom: 3%;
    left: 0;
    right: 0;
    margin: auto;
    text-align: center;
    z-index: 100;
    color: #4c4c4c;
    font-size: 20px;
    opacity: 0.5;
  }
}
::v-deep .htmltext {
  margin: -20px 0 10px 0;
  & > span {
    font-size: 26px;
    // font-weight: 700;
    letter-spacing: 0px;
    color: #003a70;
  }
  & > p {
    font-size: 14px;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 26px;
    color: rgba(0, 58, 112, 1);
    margin-top: 9px;
    span {
      display: block;
      margin-top: 6px;
    }
  }
}
@keyframes upDown {
  0% {
    margin-top: 300px;
    opacity: 0;
  }

  100% {
    margin-top: 10%;
    opacity: 1;
  }
}
.title {
  height: auto;
}
.privileges-span {
  font-size: 0.7rem;
  text-align: center;
}
</style>
